/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nextapp.echo2.webcontainer.filetransfer.commons.util;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.nio.ByteBuffer;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileWriteChannel;

import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;

import nextapp.echo2.webcontainer.filetransfer.commons.InvalidFileNameException;
import nextapp.echo2.webcontainer.filetransfer.commons.FileItem;

/** Utility class for working with streams.
 */
public final class GAEStreams {
    /**
     * Private constructor, to prevent instantiation.
     * This class has only static methods.
     */
    private GAEStreams() {
        // Does nothing
    }

    /**
     * Default buffer size for use in
     * {@link #copy(InputStream, OutputStream, boolean)}.
     */
    private static final int DEFAULT_BUFFER_SIZE = 8192;

    /**
     * Copies the contents of the given {@link InputStream}
     * to the given {@link OutputStream}. Shortcut for
     * <pre>
     *   copy(pInputStream, pOutputStream, new byte[8192]);
     * </pre>
     * @param pInputStream The input stream, which is being read.
     * It is guaranteed, that {@link InputStream#close()} is called
     * on the stream.
     * @param pOutputStream The output stream, to which data should
     * be written. May be null, in which case the input streams
     * contents are simply discarded.
     * @param pClose True guarantees, that {@link OutputStream#close()}
     * is called on the stream. False indicates, that only
     * {@link OutputStream#flush()} should be called finally.
     *
     * @return Number of bytes, which have been copied.
     * @throws IOException An I/O error occurred.
     */
    public static long copy(InputStream pInputStream,
            FileItem fileItem)
            throws IOException {

		// Again, different standard Java ways of reading from the channel.
	  
    	System.out.println("pInputStream = " + pInputStream);
    	System.out.println("fileItem = " + fileItem);

    	if(fileItem.getName() == null)
    		return 0L;
    	
    	BufferedReader reader =
          new BufferedReader(
			new InputStreamReader(pInputStream, "UTF8")); 

    	System.out.println("created reader = " + reader);

       String line = null;
	   StringBuffer sbuf = new StringBuffer();		
	   while((line = reader.readLine()) != null) {
			sbuf.append(line);
			sbuf.append("\n");
	   }  

   	System.out.println("done reading sbuf = " + sbuf);
   	System.out.println("done reading sbuf str= " + sbuf.toString());

	   long len = sbuf.toString().length(); 
	   
	   fileItem.setSize(len);

	   System.out.println("done reading sbuf len = " + len);

		AppEngineFile file = fileItem.getRepository();

		   System.out.println("AppEngineFile file = " + file);

		 // Get a file service
		  FileService fileService = FileServiceFactory.getFileService();

	  // This time lock because we intend to finalize

	   // This time lock because we intend to finalize
	  boolean lock = true;
	  FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

	   System.out.println("file channel created= ");

	  // This time we write to the channel using standard Java
	  writeChannel.write(ByteBuffer.wrap
				(sbuf.toString().getBytes()));

	   System.out.println("done writing = ");

		  // Now read from the file using the Blobstore API
		  BlobKey blobKey = fileService.getBlobKey(file);

		  System.out.println("GAESTrm Blobkey for fileupload="+blobKey);			  

	  // Now finalize
	  writeChannel.closeFinally();

	   System.out.println("done = ");

	  return len;
	
	}

}
